#include "fileio.h"
#include <stdio.h>
#include <QFile>

FileIO::FileIO(QObject *parent) :
    QObject(parent)
{

}
bool FileIO::isExited(){
    if(mSource.isEmpty()){
        emit error("source is empty");
        return false;
    }
    QFile file(mSource);
    if(file.exists()){
        file.close();
        return true;
    }else{
        file.close();
        return false;
    }
}

QString FileIO::read()
{
    if (mSource.isEmpty()){
        emit error("source is empty");
        return QString();
    }

    QFile file(mSource);
    QString fileContent("[");
    if ( file.open(QIODevice::ReadOnly) ) {
        QString line;
        QTextStream t( &file );
        do{
            line = t.readLine();
            if(!line.isNull()){
                fileContent+=',';
                fileContent+='"';
                fileContent+=line;
                fileContent+='"';
            }
        }
        while (!line.isNull());
        fileContent+="]";
        fileContent.remove(1,1);
        file.close();
    } else {
        emit error("Unable to open the file");
        return QString();
    }
    return fileContent;
}

bool FileIO::write(const QString& data)
{
    if (mSource.isEmpty())
        return false;

    QFile file(mSource);
    if (!file.open(QFile::WriteOnly|QIODevice::Append))
        return false;

    QTextStream out(&file);
    out << data;

    file.close();

    return true;
}
